package com.taotao.service.impl;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.taotao.common.utils.*;
import com.taotao.mapper.EyGoodsMapper;
import com.taotao.mapper.EyPictureMapper;
import com.taotao.mapper.EyServiceMapper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.taotao.common.enums.GoodsStatus;
import com.taotao.common.enums.ServiceStatus;
import com.taotao.common.pojo.BaseResult;
import com.taotao.pojo.EyGoods;
import com.taotao.pojo.EyPicture;
import com.taotao.pojo.EyPictureExample;
import com.taotao.pojo.EyService;
import com.taotao.service.GoodsService;
import com.taotao.service.ParamService;
import com.taotao.service.PictureService;
import com.taotao.service.WechatService;

@Service
public class PictureServiceImpl implements PictureService {

	BaseResult baseResult = new BaseResult();
	@Autowired
	EyPictureMapper eyPictureMapper;
	@Autowired
	EyGoodsMapper eyGoodsMapper;
	@Autowired
	EyServiceMapper eyServiceMapper;
	@Autowired
	GoodsService goodsService;
	@Autowired
	ParamService paramService;
	@Autowired
	WechatService wechatService;

	@Override
	public Map<String, Object> uploadPicture(HttpServletRequest request) {
		try {
			String index = request.getParameter("index");
			String type = request.getParameter("type");
			String goodsId = request.getParameter("goodsId");
			String serviceId=request.getParameter("serviceId");
			System.out.println("uploadPicture?type="+type+"&goodsId="+goodsId+"&serviceId="+serviceId+"&index="+index);
			
			MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = req.getFile("file");
			String fileName = multipartFile.getOriginalFilename();
			byte[] bs = multipartFile.getBytes();

			String uploadFilePath = paramService.getParam("upload_file_path");
			String uploadFileFolder = paramService.getParam("upload_file_folder");

			Calendar calendar = Calendar.getInstance();
			int year = calendar.get(Calendar.YEAR);
			int month = calendar.get(Calendar.MONTH) + 1;
			int day = calendar.get(Calendar.DAY_OF_MONTH);
			
			String uuid = UUID.randomUUID().toString();
			String fileNameCos = uuid + fileName.substring(fileName.lastIndexOf("."));

			String basePath="";
			if("3".equals(type)){ //聊天类型
				basePath = String.format("%s/%s/%s/%s", uploadFileFolder, year, month, day);
			}else{ // 服务类型 goods类型
				String id=StringUtils.isNotBlank(goodsId)?goodsId:serviceId;
				basePath = String.format("%s/%s/%s/%s/%s", uploadFileFolder, year, month, day, id);
			}

			uploadFilePath = String.format("%s/%s/", uploadFilePath,basePath);
			File validateCodeFolder = new File(uploadFilePath);
			if (!validateCodeFolder.exists()) {
				validateCodeFolder.mkdirs();
			}

			InputStream in = new ByteArrayInputStream(bs);
			File f = new File(uploadFilePath, fileName);// 可以是任何图片格式.jpg,.png等
			FileOutputStream fos = new FileOutputStream(f);
			byte[] b = new byte[1024];
			int nRead = 0;
			while ((nRead = in.read(b)) != -1) {
				fos.write(b, 0, nRead);
			}
			fos.close();
			in.close();
			
			String fp = uploadFilePath + fileName;
			String fpCos = uploadFilePath  + fileNameCos;

			if (StringUtils.isNotBlank(PicUtil.checkQRCode(fp))) {
				HashMap<String, String> map = new HashMap<String, String>();
				if("1".equals(type)){ //类型 1 表示goods类型的图片；2表示service类型的图片，3表示聊天类型的图片 //删除goods
					map.put("goodsId", goodsId);
					goodsService.deleteGoods(map);
				}
				FileUtils.forceDelete(new File(fp)); // 删除临时文件
				return baseResult.getErrorMap("QR code is not allowed ");
			}

			if (!this.imgCheck(fp)) {
				HashMap<String, String> map = new HashMap<String, String>();
				if("1".equals(type)){ //类型 1 表示goods类型的图片；2表示service类型的图片，3表示聊天类型的图片 //删除goods
					map.put("goodsId", goodsId);
					goodsService.deleteGoods(map);
				}
				FileUtils.forceDelete(new File(fp)); // 删除临时文件
				return baseResult.getErrorMap("The image "+(Integer.parseInt(index)+1)+" is risky ");
			}

			PicUtil.commpressPicForScale(fp, fpCos);

			String path = String.format("/%s/%s", basePath, fileNameCos);

			File fcos=new File(fpCos);
			String imageUrl = TencenUploadUtil.uploadFile(path, fcos);

			if("1".equals(type) || "2".equals(type)){ //goods类型和service类型的如picture表
				this.insertPic(index,type,goodsId,serviceId, imageUrl);
				if("0".equals(index)){//更新第一页
					this.updateImage(goodsId,serviceId, imageUrl); 
				}
			}

			FileUtils.forceDelete(new File(fp)); // 删除临时文件
//			FileUtils.forceDelete(new File(fpCos)); // 删除临时文件
			return baseResult.getSuccMap(imageUrl);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
	}

	private void updateImage(String goodsId,String serviceId, String imageUrl) {
		if(StringUtils.isNotBlank(goodsId)){
			EyGoods goods = new EyGoods();
			goods.setId(Integer.parseInt(goodsId));
			goods.setStatus(GoodsStatus.goodsStatus_1.getCode()); //在售，有图片上传成功修改就修改goods状态为开启
			goods.setImageUrl(imageUrl);
			eyGoodsMapper.updateByPrimaryKeySelective(goods);
		}else if(StringUtils.isNotBlank(serviceId)){
			EyService service = new EyService();
			service.setId(Integer.parseInt(serviceId));
			service.setStatus(ServiceStatus.serviceStatus_1.getCode()); //在售，有图片上传成功修改就修改service状态为开启
			service.setImageUrl(imageUrl);
			eyServiceMapper.updateByPrimaryKeySelective(service);
		}

	}

	private void insertPic(String index,String type, String goodsId,String serviceId, String imageUrl) {
		EyPictureExample example = new EyPictureExample();
		com.taotao.pojo.EyPictureExample.Criteria criteriaPic = example.createCriteria();
		if(StringUtils.isNotBlank(goodsId)){
			criteriaPic.andGoodsIdEqualTo(Integer.parseInt(goodsId));
		}
		if(StringUtils.isNotBlank(serviceId)){
			criteriaPic.andServiceIdEqualTo(Integer.parseInt(serviceId));
		}
		example.setOrderByClause(" id desc ");
		List<EyPicture> listPic = eyPictureMapper.selectByExample(example);
		EyPicture pic ;
		if(listPic!=null && listPic.size()>0){
			pic=listPic.get(0);
			index=String.valueOf(Integer.parseInt(pic.getImageIndex())+1);
		}else{
			index= Constants.num_0;
		}

		pic = new EyPicture();
		pic.setType(type);
		if(StringUtils.isNotBlank(goodsId)){
			pic.setGoodsId(Integer.parseInt(goodsId));
		}
		if(StringUtils.isNotBlank(serviceId)){
			pic.setServiceId(Integer.parseInt(serviceId));
		}
		String imageName=imageUrl.substring(imageUrl.lastIndexOf("/")+1);
		pic.setImageUrl(imageUrl);
		pic.setImageName(imageName);
		pic.setImageIndex(index);
		pic.setStatus(Constants.num_1); //1正常 100删除
		pic.setCreateTime(DateUtil.getDateAndTime());
		pic.setUpdateTime(DateUtil.getDateAndTime());
		eyPictureMapper.insertSelective(pic);
	}

	@Override
	public Map<String, Object> getPicture(Map<String, String> map) {
		String goodsId = map.get("goodsId");
		String serviceId = map.get("serviceId");
		String type = map.get("type");
		EyPictureExample example = new EyPictureExample();
		com.taotao.pojo.EyPictureExample.Criteria criteriaPic = example.createCriteria();
		criteriaPic.andStatusNotEqualTo(Constants.num_100); //1正常的 100删除
		if (StringUtils.isNotBlank(goodsId)) {
			criteriaPic.andGoodsIdEqualTo(Integer.parseInt(goodsId));
		}
		if (StringUtils.isNotBlank(serviceId)) {
			criteriaPic.andServiceIdEqualTo(Integer.parseInt(serviceId));
		}
		if (StringUtils.isNotBlank(type)) {
			criteriaPic.andTypeEqualTo(type);
		}
		List<EyPicture> listPic = eyPictureMapper.selectByExample(example);
		return baseResult.getSuccMap(listPic);
	}


	public boolean imgCheck(String filePath) {
		String secCheck = paramService.getParam("secCheck");
		if("false".equals(secCheck)){  //不校验，返回成功
			return true;
		}
		
		boolean returnFlag = false;
		try {
			Map<String, Object> returnMap = wechatService.getAccessTokenXcx(null);
			String accessToken = (String) returnMap.get("data");
			String url = "https://api.weixin.qq.com/wxa/img_sec_check?access_token=" + accessToken;

			// 换行符
			final String newLine = "\r\n";
			final String boundaryPrefix = "--";
			// 定义数据分隔线
			String BOUNDARY = "========7d4a6d158c9";

			URL url2 = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Charsert", "UTF-8");
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
			conn.setRequestProperty("User-Agent",
					"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
			OutputStream out = new DataOutputStream(conn.getOutputStream());

			// 上传文件
			StringBuilder sb = new StringBuilder();
			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			// 文件参数,photo参数名可以随意修改
			sb.append("Content-Disposition: form-data;name=\"image\";filename=\"" + "https://api.weixin.qq.com" + "\""
					+ newLine);
			sb.append("Content-Type:application/octet-stream");
			// 参数头设置完以后需要两个换行，然后才是参数内容
			sb.append(newLine);
			sb.append(newLine);

			out.write(sb.toString().getBytes());

			byte[] byteArray = PicUtil.toByteArray(filePath);
			// 读取文件数据
			out.write(byteArray);
			// 最后添加换行
			out.write(newLine.getBytes());

			// 定义最后数据分隔线，即--加上BOUNDARY再加上--。
			byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine).getBytes();
			// 写上结尾标识
			out.write(end_data);
			out.flush();
			out.close();
			// 定义BufferedReader输入流来读取URL的响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = reader.readLine();
			JSONObject object = JSONObject.parseObject(line);
			System.out.println("imgCheck url->"+url);
			String errcode = object.get("errcode").toString();
			System.out.println("imgCheck--->" + line);

			//errcode 的合法值  0内容正常  87014内容含有违法违规内容  87015官方文档没写，可能接口查询超时，算成功
			if("87014".equals(errcode)){
				returnFlag = false;
			}else if("40001".equals(errcode)){ //token失效 删除重试
				RedisUtils.del(WechatServiceImpl.accessToken_xcx_prefix);
				this.imgCheck(filePath);
			}else{
				returnFlag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("发送POST请求出现异常！" + e);
		}
		return returnFlag;
	}


	@Override
	@Transactional
	public Map<String, Object> deleteImages(Map<String, String> map) {
		try {
			String deleteImages=map.get("deleteImages");
			String[] imageArr = deleteImages.split(",");
//			String domain=paramService.getParam(Constants.domain);
//			String tencent_baseUrl=paramService.getParam(Constants.tencent_baseUrl);
//			String upload_file_path=paramService.getParam(Constants.upload_file_path);
			for(String image:imageArr){
				System.out.println("deleteImages imageurl-->"+image);
				String imageName=image.substring(image.lastIndexOf("/")+1);
				EyPictureExample example = new EyPictureExample();
				com.taotao.pojo.EyPictureExample.Criteria criteriaPic = example.createCriteria();
				criteriaPic.andImageNameEqualTo(imageName);
				List<EyPicture> listPic = eyPictureMapper.selectByExample(example);
				if(listPic!=null && listPic.size()>0){
					EyPicture pic = listPic.get(0);
//					String cosImageUrl=image.substring(tencent_baseUrl.length());
					//删除cos图片
//					TencenUploadUtil.deleteObject(cosImageUrl);
					//删除本地服务器记录
//					String localFile=image.replace(tencent_baseUrl,upload_file_path);
//					File f=new File(localFile);
//					if(f.exists()){
//						FileUtils.forceDelete(f);
//					}

					//删除记录
					pic.setStatus(Constants.num_100);
					pic.setUpdateTime(DateUtil.getDateAndTime());
					eyPictureMapper.updateByPrimaryKey(pic);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("删除图片异常！" + e);
		}
		return BaseResult.getSuccMap();
	}

	@Override
	public void changeDomain(List<EyPicture> listPic) {
		for(EyPicture pic:listPic){
			String imageUrl = pic.getImageUrl();
			if(StringUtils.isNotBlank(imageUrl)){
				String domain = paramService.getParam("domain");
				String tencent_baseUrl=paramService.getParam("tencent_baseUrl");
				imageUrl=imageUrl.replace(tencent_baseUrl,domain);
				pic.setImageUrl(imageUrl);
			}
		}
	}

	@Override
	public String changeDomain(String imageUrl) {
		if(StringUtils.isNotBlank(imageUrl)){
			String domain = paramService.getParam("domain");
			String tencent_baseUrl=paramService.getParam("tencent_baseUrl");
			imageUrl=imageUrl.replace(tencent_baseUrl,domain);
		}
		return imageUrl;
	}

}
